import React, { useState } from 'react';
import { arrayMoveImmutable } from 'array-move';
import { SortableContainer } from 'react-sortable-hoc';
import { SortableElement } from 'react-sortable-hoc';

import styles from './index.less';

const SortableItem = SortableElement(({ value }) => (
  <div className={styles['sortable-item']}>{value}</div>
));

const SortableList = SortableContainer(({ items }) => (
  <div>
    {items.map((value, index) => (
      <SortableItem key={`item-${index}`} index={index} value={value} />
    ))}
  </div>
));

const TestDrag = () => {
  const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3', 'Item 4']);

  const onSortEnd = ({ oldIndex, newIndex }) => {
    // setItems(arrayMove(items, oldIndex, newIndex));
    if (oldIndex !== newIndex) {
      const newData = arrayMoveImmutable(items.slice(), oldIndex, newIndex).filter(
        (el: any) => !!el,
      );
      console.log('Sorted items: ', newData);
      setItems(newData);
    }
  };

  return (
    <div className={styles['app']}>
      {/* <h2>Sortable List</h2> */}
      <SortableList items={items} onSortEnd={onSortEnd} axis="y" />
    </div>
  );
};

export default TestDrag;
